//
//  WXSearchView.swift
//  weibo
//
//  Created by 王旭 on 16/4/16.
//  Copyright © 2016年 王旭. All rights reserved.
//

import UIKit

class WXSearchView: UIView {

    @IBOutlet weak var bt_Cancel: UIButton!
    
    @IBOutlet weak var tf_Search: UITextField!
    //搜索框向右约束
    @IBOutlet weak var tf_SearchConstraint: NSLayoutConstraint!
    
    //通过类方法加载xib视图
    
    class func SearchView() -> WXSearchView {
     return NSBundle.mainBundle().loadNibNamed("WXSearchView", owner: nil, options: nil).last as! WXSearchView
    }
    
    //xib加载调用的的方法
    override func awakeFromNib() {
//        print("xib加载调用的awakeFromNib方法")
        //加载leftView
        tf_Search.leftView = leftImgView
        tf_Search.leftViewMode = .Always
        bt_Cancel.hidden = true
        
//        leftImgView.frame = CGRectMake(0, 0, bounds.size.height, bounds.size.height)
        
//代码形式设置边框
//        tf_Search.layer.borderWidth = 1
//        tf_Search.layer.borderColor = UIColor.redColor().CGColor
//        tf_Search.layer.cornerRadius = 5
//        tf_Search.clipsToBounds = true
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        leftImgView.frame = CGRectMake(0, 0, bounds.size.height, bounds.size.height)
    }
    
    //xib加载调用的的方法必须一起调用的方法(重写init方法时才会提示)
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
//        fatalError("init(coder:) has not been implemented")
    }
    
    
    //搜索框停止编辑调用方法
    @IBAction func tf_SearchEdtingEnd(sender: WXTextField) {
        bt_Cancel.hidden = true
    }
    //搜索框开始编辑调用方法
    @IBAction func tf_SearchEditingBegin(sender: UITextField) {
//        print("搜索框开始编辑了")
        //修改约束
        tf_SearchConstraint.constant = bt_Cancel.bounds.size.width
        //执行动画
        UIView.animateWithDuration(0.5) { () -> Void in
            self.layoutIfNeeded()
        }
            //按钮显示
            self.bt_Cancel.hidden = false

    }
    
    //按钮点击调用方法
    @IBAction func bt_CancelClick(sender: UIButton) {
//        print("取消按钮点击了")
        //修改约束
        tf_SearchConstraint.constant = 0
        //执行动画
        UIView.animateWithDuration(0.5) { () -> Void in
            self.layoutIfNeeded()
        }
        //取消第一响应者
        tf_Search.resignFirstResponder()
        
    }
    
     //懒加载leftView
    private lazy var leftImgView : UIImageView = {()->UIImageView in
        let leftImgView = UIImageView()
        //设置图片
        leftImgView.image = UIImage(named: "searchbar_textfield_search_icon")

        //设置内容显示模式
        leftImgView.contentMode = .Center
   
        return leftImgView
    }()
    
}
